package jpave.manager;

import java.awt.Dimension;
import java.util.Vector;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;

public class TCTable extends JTable {
	private static final long serialVersionUID = -5732180166542985071L;

	private final String [] COL_NAMES = { "TC", "Minimal Overlap", "Minimal % Identity", "Maximal Overhang" };
	
	public TCTable() {
		theModel = new TCTableModel();
		
        setAutoCreateColumnsFromModel( true );
       	setColumnSelectionAllowed( false );
       	setCellSelectionEnabled( false );
       	setRowSelectionAllowed( true );
       	setShowHorizontalLines( false );
       	setShowVerticalLines( true );	
       	setIntercellSpacing ( new Dimension ( 1, 0 ) );
       	setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       	setOpaque(true);

       	setModel(theModel);
       	
       	getTableHeader().setBackground(ManagerFrame.BGCOLOR);
	}
	
	public void addRow(String rowVal) { theModel.addRow(rowVal); }
	public void removeRow(int rowNum) { theModel.removeRow(rowNum); }
	public void clearAll() { theModel.clearAll(); }
	public String getLastRow() { return theModel.getLastRow(); }
	public String getRawRow(int row) { return theModel.getFullRow(row); }
	
	private TCTableModel theModel = null;
	
	private class TCTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 4271295746709791376L;
		
		public TCTableModel() {
			theRows = new Vector<String> ();
		}

		public void addRow(String val) { 
			theRows.add(val);
		}
		
		public void removeRow(int row) {
			theRows.remove(row);
		}
		
		public void clearAll() {
			theRows.clear();
		}
		
		public int getColumnCount() {
			return COL_NAMES.length;
		}
		
	   	public String getColumnName(int columnIndex) {
    		return COL_NAMES[columnIndex];
    	}

		public int getRowCount() {
			return theRows.size();
		}

		public Object getValueAt(int row, int col) {
			if(col == 0) return "TC" + (row + 1);
			return theRows.get(row).split(" ")[col-1];
		}
		
		public String getFullRow(int pos) { return theRows.get(pos); }
			
		public String getLastRow() {
			if(theRows.size() > 0)
				return theRows.get(theRows.size()-1);
			return "";
		}
		
		public void setValueAt(Object val, int row, int column) {
			//Check if valid first
			try {
				Integer.parseInt((String)val);
			}
			catch(Exception e) {
				return ;
			}
			
			String [] vals = theRows.get(row).split(" ");
			vals[column - 1] = (String)val;
			
			String newRow = "";
			for(int x=0; x<vals.length; x++) {
				newRow += vals[x];
				if(x<vals.length-1)
					newRow += " ";
			}
			theRows.set(row, newRow);
		}

		public boolean isCellEditable (int row, int column) { return column>0; }

		private Vector<String> theRows = null;
	}
}
